<template>
    <view>
        <TopNavigation title="房间模式管理" backText="赛程模式管理" />
        <view class="view-container">
            <view class="view-container-right">
                <view class="view-container-right-add" @click="openAddModelModal">
                    <text>添加模式</text>
                </view>
                <BoxView :titBoxObj="{
                    title: '房间模式列表',
                    titleCount: `共有${modelList.length}个模式`
                }" padding="0" style="background: #FFFFF4;">
                    <view class="view-container-right-list">
                        <view class="view-container-right-list-item-empty"
                            v-if="modelList.length === 0 && !isAddingNewModel && !loading">
                            <text>暂无模式</text>
                        </view>
                        <view class="view-container-right-list-item-empty" v-if="loading">
                            <text>加载中...</text>
                        </view>
                        <!-- 新增模式表单 -->
                        <view v-if="isAddingNewModel"
                            class="view-container-right-list-item view-container-right-list-add">
                            <view class="view-container-right-list-item-title">
                                <view class="next-row">
                                    <view class="id-value" style="width: 50%;">
                                        <text class="form-label">模式名称：</text>
                                        <input v-model="modelForm.matchRoomModelName" placeholder="请输入模式名称"
                                            class="form-input" />
                                    </view>
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">起点标识：</text>
                                        <input v-model="modelForm.startPoint" placeholder="请输入起点标识" class="form-input" />
                                    </view>
                                </view>
                                <view class="next-row">
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">终点标识：</text>
                                        <input v-model="modelForm.endPoint" placeholder="请输入终点标识" class="form-input" />
                                    </view>
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">排序：</text>
                                        <input v-model="modelForm.sort" placeholder="请输入排序值" type="number"
                                            class="form-input" />
                                    </view>
                                </view>
                                <view class="next-row">
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">准备时间：</text>
                                        <input v-model="modelForm.prepareTimeSeconds" placeholder="秒" type="number"
                                            class="form-input" />
                                    </view>
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">限制时间：</text>
                                        <input v-model="modelForm.limitTimeSeconds" placeholder="秒" type="number"
                                            class="form-input" />
                                    </view>
                                </view>
                                <view class="next-row">
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">计分模式：</text>
                                        <view class="form-picker" @click="openScoreModelPicker">
                                            {{ scoreModelOptions[modelForm.scoreModel] || '请选择' }}
                                        </view>
                                    </view>
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">对战模式：</text>
                                        <view class="form-picker" @click="openBattleModelPicker">
                                            {{ battleModelOptions[modelForm.battleModel] || '请选择' }}
                                        </view>
                                    </view>
                                </view>
                                <view class="next-button">
                                    <view class="next-button-item1" @click.stop="saveModel">提交</view>
                                    <view class="next-button-item2" @click.stop="cancelAddModel">取消</view>
                                </view>
                            </view>
                        </view>
                        <view v-if="!loading && modelList.length > 0" class="view-container-right-list-item"
                            :class="{ 'view-container-right-list-item-editing': editingModelId === model.id }"
                            v-for="model in modelList" :key="model.id">
                            <view class="view-container-right-list-item-title">
                                <!-- 编辑状态 -->
                                <template v-if="editingModelId === model.id">
                                    <view class="next-row">
                                        <view class="id-text"><text class="model-id-disabled">模式ID：</text><text class="model-id-disabled">{{ model.id }}</text></view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-value" style="width: 50%;">
                                            <text class="form-label">模式名称：</text>
                                            <input v-model="modelForm.matchRoomModelName" placeholder="请输入模式名称" class="form-input" />
                                        </view>
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">起点标识：</text>
                                            <input v-model="modelForm.startPoint" placeholder="请输入起点标识" class="form-input" />
                                        </view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">终点标识：</text>
                                            <input v-model="modelForm.endPoint" placeholder="请输入终点标识" class="form-input" />
                                        </view>
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">排序：</text>
                                            <input v-model="modelForm.sort" placeholder="请输入排序值" type="number" class="form-input" />
                                        </view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">准备时间：</text>
                                            <input v-model="modelForm.prepareTimeSeconds" placeholder="秒" type="number" class="form-input" />
                                        </view>
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">限制时间：</text>
                                            <input v-model="modelForm.limitTimeSeconds" placeholder="秒" type="number" class="form-input" />
                                        </view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">计分模式：</text>
                                            <view class="form-picker" @click="openScoreModelPicker">
                                                {{ scoreModelOptions[modelForm.scoreModel] || '请选择' }}
                                            </view>
                                        </view>
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">对战模式：</text>
                                            <view class="form-picker" @click="openBattleModelPicker">
                                                {{ battleModelOptions[modelForm.battleModel] || '请选择' }}
                                            </view>
                                        </view>
                                    </view>
                                    <view class="next-button">
                                        <view class="next-button-item1" @click.stop="saveModel">保存</view>
                                        <view class="next-button-item2" @click.stop="cancelEditModel">取消</view>
                                    </view>
                                </template>
                                <!-- 查看状态 -->
                                <template v-else>
                                    <view class="next-row">
                                        <view class="id-text"><text>模式ID：</text>{{ model.id }}</view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-value"><text>模式名称：</text>{{ model.matchRoomModelName || '未设置' }}</view>
                                        <view class="id-text"><text>起点标识：</text>{{ model.startPoint || '未设置' }}</view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text"><text>终点标识：</text>{{ model.endPoint || '未设置' }}</view>
                                        <view class="id-text"><text>排序：</text>{{ model.sort || '未设置' }}</view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text"><text>准备时间：</text>{{ formatTime(model.prepareTime) }}</view>
                                        <view class="id-text"><text>限制时间：</text>{{ formatTime(model.limitTime) }}</view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text"><text>计分模式：</text>{{ getScoreModelText(model.scoreModel) }}
                                        </view>
                                        <view class="id-text"><text>对战模式：</text>{{ getBattleModelText(model.battleModel) }}
                                        </view>
                                    </view>
                                    <view class="next-button">
                                        <view class="next-button-item1" @click.stop="editModel(model)">编辑</view>
                                        <view class="next-button-item2" @click.stop="deleteModel(model)">删除</view>
                                    </view>
                                </template>
                            </view>
                        </view>
                    </view>

                </BoxView>
            </view>
        </view>
        
        <!-- 计分模式选择弹窗 -->
        <PopuleView
            v-model="showScoreModelPicker"
            title="选择计分模式"
            :list-data="scoreModelListData"
            :selected-value="modelForm.scoreModel"
            :show-submit="false"
            @item-click="handleScoreModelSelect"
        />
        
        <!-- 对战模式选择弹窗 -->
        <PopuleView
            v-model="showBattleModelPicker"
            title="选择对战模式"
            :list-data="battleModelListData"
            :selected-value="modelForm.battleModel"
            :show-submit="false"
            @item-click="handleBattleModelSelect"
        />
        
        <!-- 删除确认弹窗 -->
        <PopuleView
            v-model="showDeleteConfirm"
            title="确认删除"
            :description="deleteConfirmText"
            :show-submit="true"
            submit-text="确认删除"
            @submit="confirmDelete"
        />
    </view>

</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { MatchRoomModelAPI } from '@/api/battle.js'
import BoxView from "@/components/UiView/BoxView.vue";
import TopNavigation from "@/components/UiView/TopNavigation.vue";
import PopuleView from "@/components/UiView/PopuleView.vue";

const loading = ref(false)
const modelList = ref([])

// 模式表单相关数据
const submitting = ref(false)
const isEditingModel = ref(false)
const currentModel = ref(null)
const editingModelId = ref(null) // 正在编辑的模式ID

// 新增模式相关
const isAddingNewModel = ref(false)

// 弹窗控制
const showScoreModelPicker = ref(false)
const showBattleModelPicker = ref(false)
const showDeleteConfirm = ref(false)
const currentDeleteModel = ref(null)
const deleteConfirmText = computed(() => {
    if (!currentDeleteModel.value) return ''
    const modelId = currentDeleteModel.value.id || currentDeleteModel.value.matchRoomModelId
    const modelName = currentDeleteModel.value.matchRoomModelName || modelId
    return `确定要删除模式 "${modelName}" 吗？`
})

// 模式表单数据
const modelForm = ref({
    matchRoomModelId: '',
    matchRoomModelName: '',
    startPoint: '',
    endPoint: '',
    prepareTimeSeconds: '',
    limitTimeSeconds: '',
    sort: 1,
    scoreModel: 0,
    battleModel: 0
})

// 得分模式映射
const scoreModelMap = {
    0: '不记分',
    1: '时间短',
    2: '时间长',
    3: '距离短',
    4: '距离长',
    5: '得分少',
    6: '得分多',
    7: '步数短',
    8: '步数长'
}

// 对战模式映射
const battleModelMap = {
    0: '接力',
    1: '单回合',
    2: '多回合'
}

const scoreModelOptions = [
    '不记分',
    '时间短',
    '时间长',
    '距离短',
    '距离长',
    '得分少',
    '得分多',
    '步数短',
    '步数长'
]

const battleModelOptions = [
    '接力',
    '单回合',
    '多回合'
]

// 转换为列表数据格式
const scoreModelListData = computed(() => {
    return scoreModelOptions.map((label, index) => ({
        id: index,
        label: label
    }))
})

const battleModelListData = computed(() => {
    return battleModelOptions.map((label, index) => ({
        id: index,
        label: label
    }))
})

const getScoreModelText = (scoreModel) => scoreModelMap[scoreModel] || '未知'
const getBattleModelText = (battleModel) => battleModelMap[battleModel] || '未知'

const formatTime = (milliseconds) => {
    if (!milliseconds) return '未设置'
    const seconds = Math.floor(milliseconds / 1000)
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    
    if (minutes > 0) {
        return `${minutes}分${remainingSeconds}秒`
    } else {
        return `${remainingSeconds}秒`
    }
}

// 加载模式列表
const loadModelList = async () => {
    loading.value = true
    try {
        const result = await MatchRoomModelAPI.page({
            pageNum: 0,
            pageSize: 100
        })
        
        console.log('API返回的完整结果:', result)
        
        if (result.code === 0 && result.data) {
            const list = result.data.list || result.data || []
            console.log('解析后的列表数据:', list)
            if (list.length > 0) {
                console.log('第一个项目的结构:', list[0])
            }
            modelList.value = list
        } else {
            modelList.value = []
            throw new Error(result.msg || '获取模式列表失败')
        }
    } catch (error) {
        console.error('获取模式列表失败:', error)
        uni.showToast({
            title: error.message || '获取模式列表失败',
            icon: 'none'
        })
    } finally {
        loading.value = false
    }
}

// 打开添加模式表单
const openAddModelModal = () => {
    isAddingNewModel.value = true
    resetModelForm()
}

// 取消添加模式
const cancelAddModel = () => {
    isAddingNewModel.value = false
    resetModelForm()
}

// 打开编辑模式
const editModel = (model) => {
    editingModelId.value = model.id
    currentModel.value = model
    fillModelForm(model)
    isEditingModel.value = true
}

// 取消编辑模式
const cancelEditModel = () => {
    editingModelId.value = null
    currentModel.value = null
    isEditingModel.value = false
    resetModelForm()
}

// 打开计分模式选择弹窗
const openScoreModelPicker = () => {
    showScoreModelPicker.value = true
}

// 打开对战模式选择弹窗
const openBattleModelPicker = () => {
    showBattleModelPicker.value = true
}

// 处理计分模式选择
const handleScoreModelSelect = (item, index) => {
    modelForm.value.scoreModel = item.id
    showScoreModelPicker.value = false
}

// 处理对战模式选择
const handleBattleModelSelect = (item, index) => {
    modelForm.value.battleModel = item.id
    showBattleModelPicker.value = false
}

// 重置模式表单
const resetModelForm = () => {
    modelForm.value = {
        matchRoomModelId: '',
        matchRoomModelName: '',
        startPoint: '',
        endPoint: '',
        prepareTimeSeconds: '',
        limitTimeSeconds: '',
        sort: 1,
        scoreModel: 0,
        battleModel: 0
    }
}

// 填充模式表单
const fillModelForm = (model) => {
    modelForm.value = {
        matchRoomModelId: model.id || model.matchRoomModelId,
        matchRoomModelName: model.matchRoomModelName || '',
        startPoint: model.startPoint || '',
        endPoint: model.endPoint || '',
        prepareTimeSeconds: model.prepareTime ? Math.floor(model.prepareTime / 1000) : '',
        limitTimeSeconds: model.limitTime ? Math.floor(model.limitTime / 1000) : '',
        sort: model.sort || 1,
        scoreModel: model.scoreModel || 0,
        battleModel: model.battleModel || 0
    }
}

// 保存模式
const saveModel = async () => {
    // 表单验证
    if (!modelForm.value.startPoint.trim()) {
        uni.showToast({
            title: '请输入起点标识',
            icon: 'none'
        })
        return
    }
    
    if (!modelForm.value.endPoint.trim()) {
        uni.showToast({
            title: '请输入终点标识',
            icon: 'none'
        })
        return
    }
    
    if (modelForm.value.startPoint === modelForm.value.endPoint) {
        uni.showToast({
            title: '起点和终点不能相同',
            icon: 'none'
        })
        return
    }
    
    if (!modelForm.value.prepareTimeSeconds || parseInt(modelForm.value.prepareTimeSeconds) <= 0) {
        uni.showToast({
            title: '请输入有效的准备时间',
            icon: 'none'
        })
        return
    }
    
    if (!modelForm.value.limitTimeSeconds || parseInt(modelForm.value.limitTimeSeconds) <= 0) {
        uni.showToast({
            title: '请输入有效的限制时间',
            icon: 'none'
        })
        return
    }
    
    const prepareTime = parseInt(modelForm.value.prepareTimeSeconds) * 1000
    const limitTime = parseInt(modelForm.value.limitTimeSeconds) * 1000
    
    if (prepareTime >= limitTime) {
        uni.showToast({
            title: '准备时间必须小于限制时间',
            icon: 'none'
        })
        return
    }
    
    // 编辑模式下的额外验证
    if (isEditingModel.value && !modelForm.value.matchRoomModelId) {
        uni.showToast({
            title: '缺少房间模型ID',
            icon: 'none'
        })
        return
    }
    
    submitting.value = true
    try {
        const data = {
            matchRoomModelName: modelForm.value.matchRoomModelName || '',
            startPoint: modelForm.value.startPoint,
            endPoint: modelForm.value.endPoint,
            prepareTime: prepareTime,
            limitTime: limitTime,
            sort: modelForm.value.sort ? parseInt(modelForm.value.sort) : 1,
            scoreModel: modelForm.value.scoreModel,
            battleModel: modelForm.value.battleModel
        }

        let result
        if (isEditingModel.value && currentModel.value) {
            result = await MatchRoomModelAPI.edit({
                ...data,
                matchRoomModelId: modelForm.value.matchRoomModelId
            })
        } else {
            result = await MatchRoomModelAPI.create(data)
        }

        if (result.code === 0) {
            uni.showToast({
                title: isEditingModel.value ? '更新成功' : '创建成功',
                icon: 'success'
            })
            
            // 清除编辑状态
            isAddingNewModel.value = false
            editingModelId.value = null
            isEditingModel.value = false
            currentModel.value = null
            resetModelForm()
            
            loadModelList()
        } else {
            throw new Error(result.msg || (isEditingModel.value ? '更新失败' : '创建失败'))
        }
    } catch (error) {
        console.error('保存模式失败:', error)
        uni.showToast({
            title: error.message || '保存失败',
            icon: 'none'
        })
    } finally {
        submitting.value = false
    }
}

// 删除模式
const deleteModel = (model) => {
    currentDeleteModel.value = model
    showDeleteConfirm.value = true
}

// 确认删除
const confirmDelete = async () => {
    if (!currentDeleteModel.value) return
    
    const modelId = currentDeleteModel.value.id || currentDeleteModel.value.matchRoomModelId
    try {
        const result = await MatchRoomModelAPI.remove({
            matchRoomModelId: modelId
        })

        if (result.code === 0) {
            uni.showToast({
                title: '删除成功',
                icon: 'success'
            })
            showDeleteConfirm.value = false
            currentDeleteModel.value = null
            loadModelList()
        } else {
            throw new Error(result.msg || '删除失败')
        }
    } catch (error) {
        console.error('删除模式失败:', error)
        uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
        })
    }
}

// 页面加载时获取数据
onMounted(() => {
    loadModelList()
})
</script>
<style lang="scss" scoped>
.view-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: calc(100vh - 65rpx);
    padding: 0 20rpx;
    overflow: hidden;


    .form-label {
        font-size: 12rpx;
        color: #333;
    }
    
    .model-id-disabled {
        color: #999 !important;
        font-size: 14rpx;
    }

    &-right {
        flex: 1;
        height: 100%;
        overflow: hidden;
        position: relative;

        &-add {
            z-index: 1000;
            position: absolute;
            color: #fff;
            top: 8rpx;
            left: 10rpx;
            font-size: 12rpx;
            border-bottom: 1rpx solid #eeeeee;

        }

        &-list {
            padding: 10rpx;
            overflow: auto;
            height: calc(100% - 60rpx);

            &-add {
                background: #FFF9E6;
            }
            
            &-item-editing {
                background: #FFF9E6;
                border: 2rpx solid #3D85EC;
            }

            &-item {
                background: #F0F0E4;
                border-radius: 10rpx;
                padding: 10rpx;
                margin-bottom: 10rpx;
                font-size: 14rpx;

                &-empty {
                    text-align: center;
                    margin-top: 80rpx;
                }


                .next-button {
                    display: flex;
                    justify-content: end;
                    align-items: center;
                    margin-top: 10rpx;

                    &-item1,
                    &-item2 {
                        width: 108rpx;
                        height: 30rpx;
                        font-size: 14rpx;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        padding-bottom: 4rpx;
                        color: #fff;
                    }


                    &-item1 {
                        background: url('/static/buttons/button2-1.png') no-repeat center center;
                        background-size: 100% 100%;
                        margin-right: 10rpx;
                    }

                    &-item2 {
                        background: url('/static/buttons/button7.png') no-repeat center center;
                        background-size: 100% 100%;
                    }
                }

                .next-row {
                    display: flex;
                    //   justify-content: space-between;
                    align-items: center;
                    margin-top: 10rpx;

                    view {
                        width: 50%;
                        display: flex;
                        align-items: center;
                    }

                    text {
                        display: inline-block;
                        font-size: 14rpx;
                        color: #99A1A4;
                        width: 70rpx;
                        text-align: right;
                        flex-shrink: 0;
                    }
                }

                .form-input {
                    flex: 1;
                    height: 30rpx;
                    padding: 0 5rpx;
                    background: #fff;
                    border-radius: 4rpx;
                    font-size: 12rpx;
                    margin-left: 10rpx;
                    margin-right: 20rpx;
                    box-sizing: border-box;
                }

                .form-picker {
                    flex: 1;
                    min-height: 30rpx;
                    padding: 0 5rpx;
                    background: #fff;
                    border-radius: 4rpx;
                    font-size: 12rpx;
                    margin-left: 10rpx;
                    display: flex;
                    align-items: center;
                    color: #333;
                    box-sizing: border-box;
                }
            }
        }
    }

}
</style>
